/* Copyright 2008. All rights reserved. */
package org.bling.parser.tags;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.jexl.Expression;
import org.apache.commons.jexl.ExpressionFactory;
import org.apache.commons.jexl.JexlContext;
import org.apache.commons.jexl.JexlHelper;
import org.bling.parser.BlingParserException;
import org.bling.parser.style.StyleParser;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Widget;

/**
 * renders an SWT Table
 * 
 * @author DISBROB
 * 
 */
public class TableTag extends Tag {

	protected Table table;
	protected String name;
	protected String style;

	public void setStyle(String style) {
		this.style = style;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}

	@Override
	public int doStartTag() throws BlingParserException {
		super.doStartTag();

		if (!(parent.getWidget() instanceof Composite)) {
			throw new BlingParserException(
					"Table tags can only be inside of composites");
		}

		Composite composite = (Composite) parent.getWidget();
		table = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		StyleParser.applyStyle((Control) getWidget(), style);
		
		return EVAL_PAGE;
	}

	@Override
	public Widget getWidget() throws BlingParserException {
		return table;
	}

	@Override
	public int doEndTag() throws BlingParserException {
		TableColumn[] columns = table.getColumns();
		
		// Load the array data into the table
		Object obj = context.getAttribute(name);
		if (obj != null && obj instanceof Collection) {
			
			Iterator<Object> items = ((Collection)obj).iterator();
			
			while (items.hasNext()) {
				Object item = items.next();
				
				List<String> values = new ArrayList<String>();
				
				for (int i = 0; i < columns.length; i++) {
					try {
						String property = (String) columns[i].getData();
						String jexlExp = "item." + property;
						Expression e = ExpressionFactory.createExpression(jexlExp);
						JexlContext jc = JexlHelper.createContext();
						jc.getVars().put("item", item);
						Object value = e.evaluate(jc);
						if (value == null) {
							value = " ";
						}
						values.add(value.toString());
					} catch (Exception e) {
						values.add(" ");
					}
				}
				
				TableItem i = new TableItem(table, SWT.NONE);
				String[] array = new String[0];
				i.setText(values.toArray(array));
				
				System.out.println("   values=" + values);
			} 
			
		}
		
		return EVAL_PAGE;
	}

}
